package com.bentley.kotlindemo.ktx

import android.content.Context
import android.net.ConnectivityManager

/**
 *
 *
 * @author lee
 * @since 2021/04/22 11:06
 */

/**
 * 是否网络在线
 */
fun Context?.isOnline(): Boolean {
    this?.apply {
        val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val netInfo = cm.activeNetworkInfo
        return netInfo != null && netInfo.isConnected
    }
    return false
}


fun Context?.isOnline(failBlock : () -> Unit  = { globalIntenetFailBock() }, successBlock : () -> Unit ) {
    this?.apply {
        val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val netInfo = cm.activeNetworkInfo
        if (netInfo != null && netInfo.isConnected){
            successBlock()
        }else{
            failBlock()
        }
    }?:failBlock()
}

fun Context?.globalIntenetFailBock(){
    // show alter to user or implement custom code here
}

// Before
//if(isOnline()){
//
//}
//
//// After
//isOnline{
//    // Do you work when connected with internet
//}
//
//// if you want to execute some code when there is no internet you can pass it as first lambda
//isOnline({
//    // Ofline
//}) {
//    // Online
//}